package com.antdesignbackend.backend.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.http.HttpClientResult;
import com.antdesignbackend.backend.common.http.HttpClientUtils;
import com.antdesignbackend.backend.common.http.HttpSession;
import com.antdesignbackend.backend.common.http.RequestType;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Fee;
import com.antdesignbackend.backend.entity.Meter;
import com.antdesignbackend.backend.entity.Middlecommand;
import com.antdesignbackend.backend.entity.entityVo.MessageData;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2020/6/8.
 */
@SuppressWarnings("unchecked")
@Service
public class LogicServiceImpl implements LogicService {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MeterService meterService;
    @Autowired
    private MiddlecommandService middlecommandService;
    @Autowired
    private FeeService feeService;
    @Override
    public String accessToken(String appid, String appsecret) {
        String token="";
        String url=String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=%s&appid=%s&secret=%s","client_credential",appid,appsecret);
        try
        {
            HttpClientResult httpClientResult= HttpClientUtils.doGet(url);
            if (httpClientResult!=null && httpClientResult.getCode() == 200) {
                String content=httpClientResult.getContent();
                JSONObject parseObject = JSONArray.parseObject(content);
                Object obj =parseObject.get("access_token");
                if(obj!=null)
                    token=obj.toString();
            }
        }catch (Exception ex)
        {
            log.error(ex.getMessage());
        }
        return token;
    }

    @Override
    public boolean onOff(Integer shopId, Integer onoff, Integer min,Integer model,Integer actionmodel) {
        boolean b=false;
        int cmd=0;
        try
        {
            String url="";
            //查出设备
            QueryWrapper<Meter> wrappmeter=new QueryWrapper<>();
            wrappmeter.eq("shopid",shopId);
            wrappmeter.eq("state",1);
            if(actionmodel>=0)
                wrappmeter.eq("model",actionmodel);
            List<Meter> meterList=meterService.list(wrappmeter);
            if(meterList.size()==0) return false;
            String command="";
            int status=0;
            for (Meter item1:meterList) {
                long random =System.currentTimeMillis();
                String dateKey =random+"";
                if(onoff==1)
                {
                    command=item1.getTurnCommand();
                }
                else
                {
                    command=item1.getOffCommand();
                }
                if(min==0)
                {
                    url=String.format("%s?topic=%s&command=%s&uid=%s", WebConfig.action_url,item1.getGateway(),command,dateKey);
                    HttpClientResult httpClientResult= HttpClientUtils.doGet(url);
                    if (httpClientResult!=null && httpClientResult.getCode() == 200) {
                        b=true;
                        status=1;
                        //修改设备状态
                        item1.setTrunOff(onoff);
                        if(model>=0)
                        {
                            item1.setModel(model);
                        }

                        meterService.updateById(item1);
                    }
                    else
                    {
                        status=-1;
                    }
                }
                  //插入命令
                Middlecommand entity = new Middlecommand();
                entity.setUid(dateKey);
                Date afterDate = CalendarDate.addDate(new Date(), "min", min);
                entity.setActionTime(afterDate);
                entity.setTopic(item1.getGateway());
                entity.setSendCommand(command);
                entity.setStatus(status);
                entity.setMeterId(item1.getId());
                entity.setCreateTime(new Date());
                entity.setShopId(item1.getShopId());
                boolean b2 = middlecommandService.save(entity);
                if (min > 0)
                    b = b2;
                if (b)
                    cmd=cmd+1;
                }
        }
        catch(Exception ex)
        {
            log.error(ex.getMessage());
        }
          if(cmd>0)
              b=true;
        return b;
    }

    @Override
    public boolean sendMessage(String openId, MessageData item) {
        boolean b = false;
        String url = "";
        String token = "";
        Map<String, Object> param = new HashMap<String, Object>();
        try
        {
            HttpSession session = new HttpSession();
            String json= JSON.toJSONString(item);//关键
            param.put("touser", openId);
            param.put("template_id", WebConfig.template_id);
            param.put("url", "http://www.baidu.com");
            param.put("data", item);
            //String par = obj.toJSONString();
            token=accessToken(WebConfig.APPID,WebConfig.AppSecret);
            url = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", token);
            HttpClientResult httpClientResult = session.doPost(url, null, param, RequestType.JSON);
            if (httpClientResult!=null && httpClientResult.getCode() == 200) {
//                String content=httpClientResult.getContent();
//                JSONObject parseObject = JSONArray.parseObject(content);
//                String code =parseObject.get("code").toString();
                b=true;
            }
        }
        catch(Exception ex)
        {
            log.error(ex.getMessage());
        }

        return b;
    }
}
